package wili.attrMapping._user.b1;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import wili.attrMapping.core.Att;
import wili.attrMapping.core.Att9;
import wili.attrMapping.core.Atts;
import wili.attrMapping.core.AttsDefine;
import wili.attrMapping.core.AttsFile;
import wili.attrMapping.core.XmlUserConf;
import wili.attrMapping.file.XmlFile;
import wili.c.Misc9a;

/**
 * 
 * @author weilai2@163.com
 *
 */
public class XmlSalesConf extends XmlUserConf {//B1JsonUserConf
	/**
	 */
	public XmlSalesConf() {
		/* 功能：根据规则文件，约束数据对象中属性间的关系。
			printRuleTemplate:
			printRule: 从数据据集D中找出各组合的最大比例，定为约束上限。数据集D当能通过生成规则的测试。
			updateTagetValue: 
		 */
		super("salesItemRules.txt", new XmlSalesDefine(true, "id", "rules", "rules"));
	}

	@Override
	public List<File> getOldFiles() {
		File[] ff = new File(DemoDIR, "xml").listFiles(f -> f.getName().endsWith("salesItems.xml"));
		return Arrays.asList(ff);
	}

	@Override
	public List<Atts> findOldAttsList(AttsDefine def, AttsFile file) {
		return super.findOldAttsList(def, file);
	}

	private List<AttsFile> newFiles;

	@Override
	public List<AttsFile> getNewAttsFiles() {
		if (newFiles == null) {
			File[] ff = new File(DemoDIR, "xml").listFiles(f -> f.getName().endsWith("salesItems.xml"));
			if (false)
				newFiles = Stream.of(ff).map(file -> attsFileOf(file)).toList();
			newFiles = Stream.of(ff).map(file -> (AttsFile) XmlFile.newInst(file)).toList();
		}
		return newFiles;
	}

	@Override
	public String genRuleOf_oldNewAtts(Atts oldAtts, Atts newAtts) {
		//仅凭一对新旧属性集实例，来猜测构造映射规则。
		Att9.usage("规则=fun(旧属性，新属性)");//
		Att inv = oldAtts.att(XmlSales9.INV);
		Att quan = oldAtts.att(XmlSales9.QUAN);
		double inv2 = Double.parseDouble(inv.value);
		double quan2 = Double.parseDouble(quan.value);
		double rate = quan2 / inv2;
		String ret = String.valueOf(Misc9a.preciseOfNum(rate, 2));
		return ret + "=" + quan2 + "/" + inv2;
	}

	protected static String standValueLR(String val) {
		val = val.trim();
		if (val.matches("\\w+"))
			return val;
		String st = AttConst.placeholderOf("?");
		val = val.replace(st, "(" + st + ")");
		if (!val.startsWith("{="))
			val = "{=" + val + "}";
		return val;
	}

	public String replaceFileContent_atLast(String st) {
		String st2 = st;
		{// eg. {/DocEntry} eq null ~>[undefined, null].includes({/DocEntry})
		 // String f = "\\{/DocEntry\\} (eq|===) null\\}|\\$\\{/DocEntry\\} === null";
			String regSt = "(\\$?)\\{/DocEntry\\}\\s+(eq|===)\\s+null";
			// String t = "[undefined, null].includes(\\$\\{/DocEntry\\})";
			String includFunSt = "[undefined, null].includes(\\$\\{/DocEntry\\})";
			st2 = st2.replaceAll(regSt, includFunSt);
			//
			regSt = regSt.replace("/DocEntry", "DocEntry");
			includFunSt = includFunSt.replace("/DocEntry", "DocEntry");
			st2 = st2.replaceAll(regSt, includFunSt);
		}
		return st2;
	}
}
